<?php


class Api extends Base_Controller
{
	public function __construct()
	{
		parent::__construct();
		
		
	}
	
	/**
	 * 
	 * 默认处理器,总处理器
	 */
	public function index()
	{

		$this->outputjson();
		$info = array();
		if(!empty($this->_json))
		{
			$info = json_decode($this->_json,TRUE);
			$objectstr = $info['data'];	
			
			if(!empty($objectstr)){
				$object = json_decode($objectstr,true);
				//print_r($object);
			}	
		}

		if(!empty($object)){
		
			$model = $this->get_api_key(trim($object['TAG']));
	
			$this->load->model('api/'.$model);
			$this->$model->outputdata($object);
		}
	}
	
	/**
	 * 
	 * 处理前段json值
	 */
	private function outputjson()
	{

		$json = file_get_contents("php://input");
		
		if(empty($json)){
			echo 'empty';
			exit;
		}else{
			
			$jarr = explode('&', $json);
			
			if(!empty($jarr))
			{
				foreach($jarr as $v){
					$strarr = explode('=', $v);
					if(!empty($strarr))
					{
						$data[$strarr[0]] = $strarr[1];
					}
				}
			}
		}

		$fp = fopen('log.txt','a+');
		fwrite($fp, '-----------------------------'."\r\n".'data1:'.$data['data']."\r\n\r\n\r\n");
		fclose($fp);
		$jsonurlencode = urldecode($data['data']);
		$tmp['data'] = $jsonurlencode;
		$this->_json = json_encode($tmp);
		$fp = fopen('log.txt','a+');
		fwrite($fp, 'data2'.$jsonurlencode."\r\n\r\n\r\n------------------------------------");
		fclose($fp);

	}
	
	/**
	 * 
	 * 取得对用model
	 * return string modelname
	 */
	private function get_api_key($key)
	{
		$apikey = array(
			'login'=>'login_mdl',
			'REWARD_LIST' => 'test_mdl',
			'LOTTERY_VIEW' => 'api_lottery_mdl',
			'LOGIN' => 'api_login_mdl',
			'MYTEST' => 'api_my_test_mdl',
			'BUY' => 'api_buy_mdl',
			'BUYRESULT' => 'api_buy_result_mdl',
			'REWARD_FINISH' => 'api_buy_finsh',
			'USER_IRECHARGE' =>'api_chongzhi_mdl',
			'REWARD_EXCHANGE' => 'api_exchange_mdl',
			'EXCHANGE_LIST' => 'api_exchange_list_mdl',
			'EXCHANGE_CONFIRM' => 'api_exchange_confirm_mdl',
			'REGISTER' => 'api_register_mdl',
			'ACTIVE' => 'api_activecode_mdl',
			'CHANGEPASSWORD' => 'api_changepassword_mdl',
			'RETPASSWORD' => 'api_retpassword_mdl',
			'RESETPASSWORD' =>'api_resetpassword_mdl',
			'USERINFOUPDATE' =>'api_userinfoupdate_mdl',
			'RECHARGE' => 'api_recharge_mdl',
			'VERSION'=>'api_update_version_mdl',
		
		);
		if(empty($apikey[$key])){
			
			echo 'API ERROR';
			exit;
		}
		
		return $apikey[$key];
	}
}